package cz.spock.cms.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cz.spock.cms.entity.CSS;
import cz.spock.core.service.BaseService;
import cz.spock.exception.InvalidDataException;
import cz.spock.exception.InvalidInputException;

@Service
public class CSSService extends BaseService {

    /**
     * name should be unique
     * 
     * @param name
     * @param description
     * @param css
     * @return
     */
    public CSS createCSS(String name, String description, String css) {
        if(name == null) {
            log.fine("name is null");
            throw new InvalidInputException("Name is required.", 412);
        }
        if(!name.endsWith(".css")) {
            name = name + ".css";
        }
        if(!isNameUnique(name)) {
            log.fine("css name (" +name+ ") is already used");
            throw new InvalidDataException("Name ("+name+") is already used.", 422);
        }
        if(css == null) {
            log.fine("css is null");
            throw new InvalidInputException("CSS is required.", 412);            
        }        
        CSS c = new CSS();
        c.setName(name);
        c.setDescription(description);
        c.setCss(css);
        c.setId(dao.put(c).getId());
        return c;
    }
    
    public boolean isNameUnique(String name) {
        if(dao.ofy().query(CSS.class).filter("name", name).get() != null) {
            return false;
        } else return true;
    }
    
    public void deleteCSS(Long id) {
        dao.delete(CSS.class, id);
    }
    
    public CSS findCSSByName(String name) {
        if(name == null) return null;
        return dao.ofy().query(CSS.class).filter("name", name).get();
    }
    
    public List<CSS> getAllStyles() {
        return dao.ofy().query(CSS.class).list();
    }
    
    public CSS getCSSById(Long id) {
        if(id == null) return null;
        return dao.get(CSS.class, id);
    }
}
